package com.example.mycarcalling.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.baidu.mapapi.search.sug.SuggestionSearchOption;
import com.example.lib_cache.adapter.EndPoiAdapter;
import com.example.lib_cache.dao.OnEndPoiNameClickListener;
import com.example.lib_cache.viewmodel.EndActivityViewModel;
import com.example.mycarcalling.R;
import com.example.mycarcalling.databinding.ActivityEndBinding;

import java.util.List;

public class EndActivity extends AppCompatActivity implements OnGetPoiSearchResultListener, OnGetSuggestionResultListener {

    private ActivityEndBinding activityEndBinding;
    private EndActivityViewModel endActivityViewModel;
    public final static String TAG = EndActivity.class.getSimpleName();

    private PoiSearch mPoiSearch;
    private SuggestionSearch mSuggestionSearch;

    private EndPoiAdapter endPoiAdapter = null;

    private int mLoadIndex;
    private int scope;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityEndBinding = DataBindingUtil
                .setContentView(this,R.layout.activity_end);

        initView();
        initData();
        initListener();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if(null != mPoiSearch){
            mPoiSearch.destroy();
        }

        if(null != mSuggestionSearch){
            mSuggestionSearch.destroy();
        }
    }

    private void initView(){
        LinearLayoutManager llm = new LinearLayoutManager(this);
        activityEndBinding.rvEndPoiItem.setLayoutManager(llm);

        endPoiAdapter = new EndPoiAdapter();
        activityEndBinding.rvEndPoiItem.setAdapter(endPoiAdapter);
        setTitle("设置终点");


    }

    private void initListener() {
        mPoiSearch.setOnGetPoiSearchResultListener(this);

        mSuggestionSearch.setOnGetSuggestionResultListener(this);

        activityEndBinding.etSelectEnd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                selectCity();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        activityEndBinding.rvEndPoiItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        endPoiAdapter.setOnEndPoiNameClickListener(new OnEndPoiNameClickListener() {
            @Override
            public void finishThisActivity() {
                setResult(2);
                finish();
            }
        });

    }

    private void initData(){
        //创建数据源
        //创建一个ViewModel的工厂
        ViewModelProvider.Factory factory = ViewModelProvider.
                AndroidViewModelFactory.getInstance(getApplication());
        //创建ViewModel的管理对象
        ViewModelProvider viewModelProvider = new ViewModelProvider(this,factory);
        //生产ViewModel
        endActivityViewModel = viewModelProvider.
                get(EndActivityViewModel.class);

        mPoiSearch = PoiSearch.newInstance();
        mSuggestionSearch = SuggestionSearch.newInstance();


        endActivityViewModel.loadingData();
        activityEndBinding.setEndMapCity(endActivityViewModel);
        activityEndBinding.setLifecycleOwner(this);
    }

    /**
     * 发起请求
     */
    private void selectCity(){
        // 发起请求
        String keywordStr = activityEndBinding.etSelectEnd
                .getText().toString().trim();
        if(TextUtils.isEmpty(keywordStr)){
            return;
        }
        Log.d(TAG,keywordStr);
        mLoadIndex = 10;
        scope = 2;
        mPoiSearch.searchInCity((new PoiCitySearchOption())
                .city(activityEndBinding.tvEndCity.getText().toString().trim())
                .keyword(keywordStr)
                .pageNum(mLoadIndex) // 分页编号
                .cityLimit(true)
                .scope(scope));

        mSuggestionSearch.requestSuggestion(new SuggestionSearchOption()
                .city(activityEndBinding.tvEndCity.getText().toString().trim())
                .keyword(keywordStr));

    }

    @Override
    public void onGetPoiResult(PoiResult poiResult) {
        if (poiResult == null || poiResult.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
//            Toast.makeText(EndActivity.this,
//                    "未找到结果", Toast.LENGTH_LONG).show();
            return;
        }

        List<PoiInfo> poiInfos = poiResult.getAllPoi();
        if (null == poiInfos) {
            return;
        }
        Log.d(TAG,String.valueOf("poiResult"+poiInfos.size()));

        // 隐藏之前的
//        hidePoiInfoLayout();

//        mRecyclerView.setVisibility(View.VISIBLE);
    }

    @Override
    public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {

    }

    @Override
    public void onGetPoiDetailResult(PoiDetailSearchResult poiDetailSearchResult) {

    }

    @Override
    public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

    }

    @Override
    public void onGetSuggestionResult(SuggestionResult suggestionResult) {
        if(null == suggestionResult
                || suggestionResult.error == SearchResult.ERRORNO.RESULT_NOT_FOUND){
            mLoadIndex = 0;
            Toast.makeText(EndActivity.this,
                    "未找到地点", Toast.LENGTH_LONG).show();
            return;
        }
        Toast.makeText(EndActivity.this,
                "已找到地点", Toast.LENGTH_LONG).show();

        List<SuggestionResult.SuggestionInfo> suggestionInfos
                = suggestionResult.getAllSuggestions();
        if(null == suggestionInfos){
            Log.d("得到推荐1",suggestionInfos.toString());

            return;
        }
        Log.d(TAG,String.valueOf("Suggestion"+suggestionInfos.size()));

        activityEndBinding.rvEndPoiItem.setVisibility(View.VISIBLE);

        if(null == endPoiAdapter){
            Log.d("得到推荐2",suggestionInfos.toString());
            endActivityViewModel.suggestionResultToPoiList(suggestionInfos);
            endPoiAdapter = new EndPoiAdapter(
                    endActivityViewModel.getEndPoiListLiveData().getValue());
//            activityStartBinding.rvPoiItem.setAdapter(poiAdapter);
        }else {
            Log.d("得到推荐3",suggestionInfos.toString());

            endActivityViewModel.suggestionResultToPoiList(suggestionInfos);
            endPoiAdapter.updateData(
                    endActivityViewModel.getEndPoiListLiveData().getValue());
        }
    }


}
